package com.kgc.xsConsumer.controller;

import com.kgc.basic.util.ResponseMsg;
import com.kgc.xs.pojo.SalesInvoice;
import com.kgc.xsConsumer.feign.ImportExportFeign;
import com.kgc.xsConsumer.feign.SalesInvoiceFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;

@RestController
@RequestMapping("/salesInvoice")
@CrossOrigin
public class SalesInvoiceController {

    private Logger logger = LoggerFactory.getLogger(SalesInvoiceController.class);

    @Autowired
    private SalesInvoiceFeign salesInvoiceFeign;

    @Autowired
    private ImportExportFeign importExportFeign;


    @RequestMapping("insertMainSalesInvoice")
    public ResponseMsg insertMainSalesInvoice(@RequestBody SalesInvoice salesInvoice) {
        return salesInvoiceFeign.insertMainSalesInvoice(salesInvoice);
    }

    @RequestMapping("selectSalesInvoiceByPage")
    public ResponseMsg selectSalesInvoiceByPage(@RequestBody Map<String, Object> map) {
        logger.info("consumer SalesInvoiceController selectSalesInvoiceByPage map:{}", map);
        return salesInvoiceFeign.selectSalesInvoiceByPage(map);
    }

    @RequestMapping("deleteSalesInvoice")
    public ResponseMsg deleteSalesInvoice(@RequestParam("id") String id) {
        logger.info("consumer SalesInvoiceController deleteSalesInvoice id:{}", id);
        return salesInvoiceFeign.deleteSalesInvoice(Integer.parseInt(id));
    }

            @RequestMapping("insertSalesInvoice")
    public ResponseMsg insertSalesInvoice(@RequestBody Map<String, Object> map) {
        logger.info("consumer insertSalesInvoice map:{}", map);
        return salesInvoiceFeign.insertSalesInvoice(map);
    }

    @RequestMapping("selectSalesOutByCid")
    public ResponseMsg selectSalesOutByCid(@RequestParam("customerId") String customerId) {
        logger.info("consumer selectSalesOutByCid customerId:{}", customerId);
        return salesInvoiceFeign.selectSalesOutByCid(Integer.parseInt(customerId));
    }

    @RequestMapping("selectSalesOutByCode")
    public ResponseMsg selectSalesOutByCode(@RequestParam("code") String code) {
        logger.info("consumer selectSalesOutByCode code:{}", code);
        return salesInvoiceFeign.selectSalesOutByCode(code);
    }

    //回显
    @RequestMapping("selectSalesInvoiceByCode")
    public ResponseMsg selectSalesInvoiceByCode(@RequestParam("code") String code) {
        logger.info("consumer selectSalesInvoiceByCode code:{}", code);
        return salesInvoiceFeign.selectSalesInvoiceByCode(code);
    }

    //回显（明细）
    @RequestMapping("selectSalesInvoiceDetailByCode")
    public ResponseMsg selectSalesInvoiceDetailByCode(@RequestParam("invoiceCode") String invoiceCode) {
        logger.info("consumer selectSalesInvoiceDetailByCode:{}", invoiceCode);
        return salesInvoiceFeign.selectSalesInvoiceDetailByCode(invoiceCode);
    }

    @RequestMapping("deleteBeforeUpdate")
    public ResponseMsg deleteBeforeUpdate(@RequestParam("code") String code) {
        logger.info("consumer deleteBeforeUpdate code:{}", code);
        ResponseMsg msg = salesInvoiceFeign.deleteSalesInvoiceByCode(code);
        ResponseMsg msg1 = salesInvoiceFeign.deleteSalesDetailsByCode(code);
        msg1.setData(msg);
        return msg;
    }

    @RequestMapping("getOutStoreList")
    public ResponseMsg getOutStoreList(@RequestBody Map<String, Object> map) {
        logger.info("consumer getOutStoreList map:{}", map);
        return salesInvoiceFeign.getOutStoreList(map);
    }

    //下载模板
    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public void downTemplate(HttpServletResponse response) {
        logger.info("consumer CustomerController downTemplate is start...");
        try {
            ResponseMsg responseMsg = importExportFeign.downLoadTemplate("com.kgc.xs.pojo.SalesInvoice");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] templateData = Base64.getDecoder().decode(base64Data);   //解码

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("客户信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(templateData);
            } else {
                logger.error("下载模板失败, status: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer CustomerController downTemplate is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    //导入
    @RequestMapping(value = "/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseMsg importInfo(@RequestPart("file") MultipartFile file) {
        logger.info("consumer CustomerController importInfo fileName:{}", file.getOriginalFilename());
        return importExportFeign.importInfo(file, "com.kgc.xs.pojo.SalesInvoice", "code", "salesInvoiceServiceImpl");
    }

    @RequestMapping(value = "/export")
    public void exportSalesInvoices(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer SalesInvoiceController exportSalesInvoices params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.xs.pojo.SalesInvoice", "create_date desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("销售发票信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesInvoiceController exportSalesInvoices is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping(value = "/print", method = RequestMethod.POST)
    public void printSalesInvoices(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer SalesInvoiceController printSalesInvoices params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.printEntitiesToPDF(map, "com.kgc.xs.pojo.SalesInvoice", "create_date desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] pdfData = Base64.getDecoder().decode(base64Data);

                response.setContentType("application/pdf");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("销售发票信息表.pdf", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(pdfData);
            } else {
                logger.error("打印失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesInvoiceController printSalesInvoices is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
